package com.hwadee.backend.controller;

import com.hwadee.backend.entity.Result;
import com.hwadee.backend.entity.user.User;
import com.hwadee.backend.service.UserService;
import com.hwadee.backend.service.AuthorizeService;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/doctors")
public class DoctorController {

    private final UserService userService;
    private final AuthorizeService authorizeService;

    @Autowired
    public DoctorController(UserService userService, AuthorizeService authorizeService) {
        this.userService = userService;
        this.authorizeService = authorizeService;
    }

    @GetMapping("/patients")
    public Result getAuthorizedPatients() {
        // 查询所有角色为"用户"的患者
        List<User> patients = userService.getUsersByRole("用户");
        
        // 转换为只包含id和username的对象列表
        List<PatientOption> patientOptions = patients.stream()
                .map(user -> new PatientOption(user.getId(), user.getUsername()))
                .collect(Collectors.toList());
        
        // 构建包含patients键的响应数据
        Map<String, Object> responseData = new HashMap<>();
        responseData.put("patients", patientOptions);
        
        return Result.success(responseData);
    }

    @GetMapping("/patients/{patientId}/data/{doctorId}")
    public Result getPatientData(@PathVariable int patientId, @PathVariable int doctorId) {
        try {
            // 检查授权状态
            String status = authorizeService.getAuthorizationStatus(doctorId, patientId);
            if (status == null || !"approved".equals(status)) {
                return Result.error("未获得患者授权");
            }
            // 查询患者信息
            User patient = userService.getUserById((long)patientId);
            if (patient == null) {
                return Result.error("患者不存在");
            }
            // 返回患者数据
            return Result.success(patient);
        } catch (Exception e) {
            return Result.error("获取患者数据失败:未获取该病人权限");
        }
    }

    // 内部静态类用于封装返回给前端的患者选项数据
    private static class PatientOption {
        private int id;
        private String name;

        public PatientOption(int id, String name) {
            this.id = id;
            this.name = name;
        }

        // Getters
        public int getId() { return id; }
        public String getName() { return name; }
    }
}